package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.mapper.OrderInfoMapper;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import cn.wolfcode.shop.cloud.util.IdGenerateUtil;
import cn.wolfcode.shop.cloud.util.SeckillCodeMsg;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderInfoServiceImpl implements IOrderInfoService {
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Override
    @Transactional
    public String doSeckill(Long userId, Long seckillId) {
        //减少真实库存
        int row = seckillGoodService.decrCount(seckillId);
        if(row==0){
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //创建订单对象保存到数据库中
        String orderNo=creatOrder(userId,seckillId);
        //往t_seckill_order表中插入一条数据
        seckillOrderService.creatSeckillOrder(userId,seckillId,orderNo);
        return orderNo;
    }

    @Override
    public OrderInfo getOrderInfoByOderNo(String orderNo) {

        return orderInfoMapper.findByOrderNo(orderNo);

    }



    @Override
    public int changOrderInfoStatus(String orderNo, Integer status) {
        return orderInfoMapper.changOrderInfoStatus(orderNo,status);


    }



    @Override
    public void updateOrderStatus(String orderNo, Integer status) {
        orderInfoMapper.updateOrderStatus(orderNo,status);
    }

    private String creatOrder(Long userId,Long seckillId) {
        //创建出来一个订单,并且把订单信息保存到数据库中;
        OrderInfo orderInfo=new OrderInfo();
        SeckillGoodVO seckillGoodVo = seckillGoodService.queryById(seckillId);
        BeanUtils.copyProperties(seckillGoodVo,orderInfo);
        orderInfo.setUserId(userId);
        orderInfo.setCreateDate(new Date());
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId()+"");
        orderInfoMapper.save(orderInfo);
        return orderInfo.getOrderNo();
    }
}
